<?php

namespace app\common;

use Mpdf\Mpdf;

class CustomMPDF
{
    protected $mpdf;
    protected $shadowCallback;
    protected $containerConfig;

    public function __construct($config = [])
    {
        // 默认配置 - 简化字体设置
        $defaultConfig = [
            'mode' => 'utf-8',
            'format' => 'A4',
            'default_font_size' => 11,
            'margin_left' => 15,
            'margin_right' => 15,
            'margin_top' => 15,
            'margin_bottom' => 25,
            'margin_header' => 0,
            'margin_footer' => 0,
            'orientation' => 'P',
            'tempDir' => sys_get_temp_dir(),
            'autoScriptToLang' => true,
            'autoLangToFont' => true,
        ];

        $config = array_merge($defaultConfig, $config);
        $this->mpdf = new Mpdf($config);
    }

    public function setShadowCallback($callback)
    {
        $this->shadowCallback = $callback;
    }

    public function setContainerConfig($config)
    {
        $this->containerConfig = $config;
    }

    // 获取当前页码
    public function getPage()
    {
        return $this->mpdf->page;
    }

    // 获取页面宽度
    public function getPageWidth()
    {
        return $this->mpdf->w;
    }

    // 获取页面高度  
    public function getPageHeight()
    {
        return $this->mpdf->h;
    }

    // 设置文档信息
    public function SetCreator($creator)
    {
        $this->mpdf->SetCreator($creator);
    }

    public function SetAuthor($author)
    {
        $this->mpdf->SetAuthor($author);
    }

    public function SetTitle($title)
    {
        $this->mpdf->SetTitle($title);
    }

    // 兼容TCPDF的方法
    public function setPrintHeader($bool)
    {
        if (!$bool) {
            $this->mpdf->SetHTMLHeader('');
        }
    }

    public function setPrintFooter($bool)
    {
        if (!$bool) {
            $this->mpdf->SetHTMLFooter('');
        }
    }

    public function SetAutoPageBreak($auto, $margin = 0)
    {
        $this->mpdf->SetAutoPageBreak($auto, $margin);
    }

    public function setCellHeightRatio($ratio)
    {
        // mPDF中可能不需要这个设置
    }

    public function AddPage($orientation = '', $size = '', $rotationAngle = 0)
    {
        return $this->mpdf->AddPage($orientation, $size, $rotationAngle);
    }

    // 生成阴影HTML
    public function generateShadowHtml()
    {
        // 禁用阴影效果
        return;

        // 获取当前页码
        $currentPage = $this->getPage();

        // 基础参数
        $containerW = 180; // mm
        $containerX = 15;  // mm

        // 根据页码设置不同的高度和Y坐标
        if ($currentPage == 1) {
            $containerH = 238; // 第一页高度
            $containerY = 45;  // 第一页Y坐标 - 从title下面一点点位置开始
        } else {
            $containerH = 270; // 其他页面高度
            $containerY = 12;  // 其他页面Y坐标
        }

        $radius = 8 * 0.2646; // px转mm

        // 生成阴影和容器的HTML
        $shadowHtml = sprintf(
            '
            <div style="position: absolute; left: %dmm; top: %dmm; width: %dmm; height: %dmm; 
                       background-color: rgba(0,0,0,0.15); border-radius: %dmm; z-index: 1;"></div>
            <div style="position: absolute; left: %dmm; top: %dmm; width: %dmm; height: %dmm; 
                       background-color: rgba(0,0,0,0.15); border-radius: %dmm; z-index: 1;"></div>
            <div style="position: absolute; left: %dmm; top: %dmm; width: %dmm; height: %dmm; 
                       background-color: rgba(0,0,0,0.2); border-radius: %dmm; z-index: 2;"></div>
            <div style="position: absolute; left: %dmm; top: %dmm; width: %dmm; height: %dmm; 
                       background-color: rgba(0,0,0,0.2); border-radius: %dmm; z-index: 2;"></div>
            <div style="position: absolute; left: %dmm; top: %dmm; width: %dmm; height: %dmm; 
                       background-color: white; border-radius: %dmm; z-index: 4;"></div>',
            $containerX + 2,
            $containerY + 2,
            $containerW,
            $containerH,
            $radius,
            $containerX - 1,
            $containerY - 1,
            $containerW,
            $containerH,
            $radius,
            $containerX + 1.5,
            $containerY + 1.5,
            $containerW,
            $containerH,
            $radius,
            $containerX - 0.5,
            $containerY - 0.5,
            $containerW,
            $containerH,
            $radius,
            $containerX,
            $containerY,
            $containerW,
            $containerH,
            $radius
        );

        $this->mpdf->WriteHTML($shadowHtml);
    }

    // 插入背景图片
    public function insertBackgroundImage($file, $x = 0, $y = 0, $w = 0, $h = 0)
    {
        if (file_exists($file)) {
            // 使用mPDF的Image方法直接插入背景图片
            // 确保图片从页面最顶部开始显示
            $this->mpdf->Image($file, $x, $y, $w, $h, '', '', true, false, 0, 'C', false, false, 0, false, false, false);
        }
    }

    // 设置标题
    public function insertTitle($font, $title, $containerX, $containerY, $containerW)
    {
        // 标题应该显示在橙色背景区域内，居中显示
        $titleX = 105; // A4纸宽度210mm的一半，居中显示
        $titleY = 26;  // 向上调整标题位置

        $titleHtml = sprintf(
            '
            <div style="position: absolute; left: %dmm; top: %dmm; font-family: %s; font-size: 24pt; 
                       font-weight: bold; color: black; text-align: center; z-index: 4; width: 200mm; margin-left: -75mm; white-space: nowrap;">%s</div>',
            $titleX,
            $titleY,
            $font,
            $title
        );

        $this->mpdf->WriteHTML($titleHtml);
    }

    // 写入HTML内容到指定位置
    public function writeHTMLCell($w, $h, $x, $y, $html, $border = 0, $ln = 0, $fill = false, $reseth = true, $align = '', $autopadding = true)
    {
        // 对于mPDF，我们使用WriteHTML方法
        $this->mpdf->WriteHTML($html);
    }

    public function WriteHTML($html)
    {
        return $this->mpdf->WriteHTML($html);
    }

    // 输出PDF
    public function Output($name = '', $dest = 'I')
    {
        // 如果是浏览器内联显示，确保设置正确的HTTP头
        if ($dest == 'I' && !headers_sent()) {
            header('Content-Type: application/pdf');
            header('Content-Disposition: inline; filename="' . urlencode($name) . '"');
            header('Cache-Control: private, max-age=0, must-revalidate');
            header('Pragma: public');
        }

        return $this->mpdf->Output($name, $dest);
    }

    public function OutputPDF($dest = 'I', $name = '')
    {
        // 修复参数顺序问题
        // 如果第一个参数看起来像文件路径，则交换参数
        if (is_string($dest) && (strpos($dest, '/') !== false || strpos($dest, '\\') !== false)) {
            // 第一个参数是文件路径，第二个是模式
            $filePath = $dest;
            $mode = $name;
            return $this->mpdf->Output($filePath, $mode);
        } else {
            // 正常的参数顺序：模式，文件名
            return $this->mpdf->Output($name, $dest);
        }
    }

    // 兼容方法
    public function getMargins()
    {
        return [
            'left' => $this->mpdf->lMargin,
            'top' => $this->mpdf->tMargin,
            'right' => $this->mpdf->rMargin
        ];
    }

    public function Image($file, $x = '', $y = '', $w = 0, $h = 0, $type = '', $link = '')
    {
        // 在mPDF中插入图片
        $this->mpdf->Image($file, $x, $y, $w, $h, $type, $link);
    }

    public function SetFont($family, $style = '', $size = 0)
    {
        return $this->mpdf->SetFont($family, $style, $size);
    }

    public function Cell($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
    {
        // mPDF没有Cell方法，我们用WriteHTML模拟
        $this->mpdf->WriteHTML("<div style='width:{$w}px; height:{$h}px;'>$txt</div>");
    }

    public function Ln($h = null)
    {
        $this->mpdf->WriteHTML('<br/>');
    }

    public function SetXY($x, $y)
    {
        // mPDF中位置设置通过CSS实现
        $this->mpdf->WriteHTML("<div style='position:absolute; left:{$x}px; top:{$y}px;'></div>");
    }

    public function GetX()
    {
        return 0; // mPDF中没有直接的位置获取方法
    }

    public function GetY()
    {
        return 0; // mPDF中没有直接的位置获取方法
    }

    // 魔术方法，将未定义的方法调用转发给mPDF实例
    public function __call($method, $args)
    {
        if (method_exists($this->mpdf, $method)) {
            return call_user_func_array([$this->mpdf, $method], $args);
        }

        throw new \BadMethodCallException("Method $method does not exist");
    }
}
